import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { PdfComponent } from '@delon/abc/pdf';

import { Api } from '../api';

@Component({
  selector: 'app-preview-pdf',
  template: ` <div style="text-align: center; height: 800px; overflow-y: scroll">
    <div style="text-align: center">
      <pdf [src]="pdfSrc" autoReSize fitToPage />
    </div>
    @if (!pdfSrc) {
      <div>
        <span class="font-bold text-3xl text-gray-500">暂无pdf</span>
      </div>
    }
  </div>`,
  changeDetection: ChangeDetectionStrategy.Default,
  standalone: true,
  imports: [PdfComponent, CommonModule]
})
export class PdfPreviewComponent implements OnInit {
  @Input() record: any = {};

  pdfPreviewUrl: string = `${Api.BasePreviewApi}/`;

  pdfSrc: string = '';
  @ViewChild('pdfContainer') pdfContainer: ElementRef | undefined;
  constructor(
    private httpClient: HttpClient,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    if (this.record && this.record.id) {
      const url = this.pdfPreviewUrl + this.record.id;
      this.httpClient.get(url, { responseType: 'blob' }).subscribe(blob => {
        // TODO
        const reader = new FileReader();
        reader.onload = (e: ProgressEvent<FileReader>) => {
          // 方法一
          // this.pdfSrc = e.target!.result as string;
          // this.cdr.detectChanges();
          // 方法二
          const obj = new Blob([blob]);
          this.pdfSrc = window.URL.createObjectURL(obj);
        };
        reader.readAsArrayBuffer(blob);
      });
    }
  }
}
